package com.milkcoffee.jvm.lesson01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author zxs
 */
public class CustomizeClassloader extends ClassLoader{

    private String classPath;

    private String fm = "%s/%s.class";

    public CustomizeClassloader(String classPath){
        this.classPath  = classPath;
    }

    private byte[] findClassFileByte(String classFullName) throws IOException {

        //类全路径
        String classFullNamePath = classFullName.replaceAll("\\.","/");
        String path = String.format(fm,classPath,classFullNamePath);

        FileInputStream stream = new FileInputStream(path);
        int len = stream.available();

        byte[] resultByte = new byte[len];
        stream.read(resultByte);
        stream.close();

        return resultByte;
    }

    /**
     * 在CustomizeClassloader中调用的loadclass的时候会调用这个方法
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {

            byte[] fileByte = findClassFileByte(name);
            return defineClass(name,fileByte,0,fileByte.length);
        } catch (IOException e) {
            // 加载出错
            e.printStackTrace();
        }

        return null;
    }
}
